<template>
    <div>
        <!-- <div>
            <button @click="printEditorHtml">print html</button>
            <button @click="insertTextHandler">insert text</button>
            <button @click="disableHandler">disable</button>
        </div> -->
        <div style="border: 1px solid #ccc; margin-top: 10px;">
            <!-- 工具栏 -->
            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig" />
            <!-- 编辑器 -->
            <Editor style="height: 400px; overflow-y: hidden;" :defaultConfig="editorConfig" v-model="html"
                @onChange="onChange" @onCreated="onCreated" />
        </div>
    </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import * as qiniu from 'qiniu-js'
export default {
    name: 'MyEditor',
    components: { Editor, Toolbar },
    props: {
        content: {
            type: String,
            default: ''
        },
        token: {
            type: String,
            default: ''
        },
        upload: {
            type: String,
            default: ''
        },
        url: {
            type: String,
            default: ''
        },

    },
    data() {
        return {
            editor: null,
            html: this.content,
            toolbarConfig: {
            },
            editorConfig: {
                placeholder: '请输入内容...',
                MENU_CONF: {
                    // 配置上传图片
                    uploadImage: {

                    },
                    uploadVideo: {

                    }
                },

            },
            // token: '',
            // upload: '',
            // url: ''
        }
    },
    watch: {
        content(newVal, oldVal) {
            console.log(newVal)
            this.html = newVal
        }
    },
    created() {
        let that = this
        // that.init()
        let template=this.template
        this.editorConfig.MENU_CONF['uploadImage'] = {
            // 自定义上传
            // async customUpload(file: File, insertFn: InsertFnType) {  // TS 语法
            async customUpload(file, insertFn) {
                let types = file.name.split('.')//获取格式
                let key = template +'/home/'  + new Date().valueOf() + '.' + types[types.length - 1];
                let config = {
                    useCdnDomain: true, //表示是否使用 cdn 加速域名，为布尔值，true 表示使用，默认为 false。
                    region: null // 根据具体提示修改上传地区,当为 null 或 undefined 时，自动分析上传域名区域
                };
                const observable = qiniu.upload(file, key, that.token, config);  //this.qiniuToken 由后端提供，通过接口获取
                observable.subscribe({
                    complete: (result) => {
                        // console.log('result', result)
                        // 利用七牛云注册成功后配置的地址 + 七牛云返回唯一的key，访问上传到七牛云的图片。
                        let url = `${that.url}${result.key}`;
                        // that.init()
                        insertFn(url, '走丢啦', url); // 将图片插入编辑器显示
                    }
                })

            }
        }
        this.editorConfig.MENU_CONF['uploadVideo'] = {
            // 自定义上传// TS 语法
            async customUpload(file, insertFn) {
                let types = file.name.split('.')//获取格式
                let key = template +'/home/' + new Date().valueOf() + '.' + types[types.length - 1];
                let config = {
                    useCdnDomain: true, //表示是否使用 cdn 加速域名，为布尔值，true 表示使用，默认为 false。
                    region: null // 根据具体提示修改上传地区,当为 null 或 undefined 时，自动分析上传域名区域
                };
                const observable = qiniu.upload(file, key, that.token, config);  //this.qiniuToken 由后端提供，通过接口获取
                observable.subscribe({
                    complete: (result) => {
                        // console.log('result', result)
                        // 利用七牛云注册成功后配置的地址 + 七牛云返回唯一的key，访问上传到七牛云的图片。
                        let url = `${that.url}${result.key}`;
                        // that.init()
                        insertFn(url) // 将图片插入编辑器显示
                    }
                })
                // insertFn(url, poster)
            }
        }
    },
    methods: {
         init() {
            this.getToken().then(res => {
                this.token = res.data.token
                this.upload = res.data.upload
                this.url = res.data.url
                // console.log(res)
            },
                function () {
                    console.log('请求失败处理');
                }
            )
        },
        destroy() {
            const editor = this.editor
            if (editor == null) return
            editor.destroy()
        },

        getUploadToken() {
            // return 'abc'
        },
        onCreated(editor) {
            this.editor = Object.seal(editor) // 【注意】一定要用 Object.seal() 否则会报错
        },
        onChange(editor) {
            if (editor.getHtml() == '<p><br></p>') {
                this.$emit('getContent', '')
            } else {
                this.$emit('getContent', editor.getHtml())
            }
            // console.log('onChange', editor.getHtml())
            // onChange 时获取编辑器最新内容
        },
        insertTextHandler() {
            const editor = this.editor
            if (editor == null) return
            editor.insertText(' hello ')
        },
        printEditorHtml() {
            const editor = this.editor
            if (editor == null) return
            // console.log(editor.getHtml())
        },
        disableHandler() {
            const editor = this.editor
            if (editor == null) return
            editor.disable()
        }
    },
    mounted() {
        // 模拟 ajax 请求，异步渲染编辑器
        setTimeout(() => {
            // console.log(this.content)
            this.html = this.content
        }, 500)
    },
    beforeDestroy() {
        const editor = this.editor
        if (editor == null) return
        editor.destroy() // 组件销毁时，及时销毁 editor ，重要！！！
    },
}
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
